<template>
  <el-container>
    <!-- home header -->
    <el-header class="index-el-header">
      <div class="div-index-header">
        <div class="div-index-header-logo">
          <h1>
            <img src="../../public/index-logo.png" alt="" />
          </h1>
        </div>
        <div class="div-index-header-nav">
          <div class="div-index-header-nav-item">
            <el-input placeholder="搜索">
              <template #suffix>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-search"
                  class="el-button-search"
                ></el-button>
              </template>
              ></el-input
            >
          </div>
          <div class="div-index-header-nav-item">
            <el-button
              icon="el-icon-document"
              size="mini"
              type="text"
              class="el-button-help"
              >支持与文档</el-button
            >
          </div>
          <div class="div-index-header-nav-item">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-message-solid"
            ></el-button>
          </div>
          <div class="div-index-header-nav-item">
            <el-button type="text" size="mini">
              <div style="display:flex;align-items:center ">
                <h1>
                  <img
                    src="../../public/icon-user.png"
                    alt=""
                    class="icon-user"
                  />
                </h1>
                <span style="margin:0 20px 0 5px">{{ nowUserName }}</span>
                <i class="el-icon-edit"> </i>
              </div>
            </el-button>
          </div>
          <div class="div-index-header-nav-item">
            <el-button
              type="text"
              icon="el-icon-switch-button"
              @click="clickLogoutButton"
            >
              退出登录
            </el-button>
          </div>
        </div>
      </div>
    </el-header>
    <!-- home page -->
    <el-container>
      <!-- aside -->
      <el-aside id="el-aside-nav" width="191px">
        <div class="div-index-aside-nav">
          <div class="div-index-aside-nav-item">
            <el-button
              type="text"
              size="mini"
              class="el-button-hide-aside"
              style="padding:0"
              icon="el-icon-s-fold"
            >
            </el-button>
          </div>
          <!-- project -->
          <div class="div-index-aside-nav-item">
            <el-button
              type="text"
              @click="toProjectSystem()"
              :icon="
                nowAsideNavIndex == 0
                  ? 'el-icon-projectsystem-focus'
                  : 'el-icon-projectsystem'
              "
            >
            </el-button>
          </div>
          <div class="div-index-aside-nav-item">
            <el-button
              type="text"
              @click="toIncomeStreamSystem()"
              :icon="
                nowAsideNavIndex == 1
                  ? 'el-icon-incomestreamsystem-focus'
                  : 'el-icon-incomestreamsystem'
              "
            >
            </el-button>
          </div>
          <div class="div-index-aside-nav-item">
            <el-button
              type="text"
              @click="toOutlayStreamSystem"
              :icon="
                nowAsideNavIndex == 2
                  ? 'el-icon-outlaystreamsystem-focus'
                  : 'el-icon-outlaystreamsystem'
              "
            >
            </el-button>
          </div>
          <div class="div-index-aside-nav-item">
            <el-button
              type="text"
              @click="toAdminSystem()"
              :icon="
                nowAsideNavIndex == 3
                  ? 'el-icon-adminsystem-focus'
                  : 'el-icon-adminsystem'
              "
            >
            </el-button>
          </div>
        </div>
      </el-aside>
      <!-- main and footer -->
      <el-container>
        <el-main :style="{ minHeight: minHeight + 'px' }">
          <!-- router -->
          <router-view />
        </el-main>
        <el-footer>
          <div class="div-footer">
            <div class="div-footer-line1">
              <el-button type="text" size="mini">后台</el-button>
              <el-button type="text" size="mini">帮助</el-button>
              <el-button type="text" size="mini"
                >网络教育学院培训项目管理系统V1.0</el-button
              >
            </div>
            <div class="div-footer-line2">
              <span>Copyright 2021 华南师范大学</span>
            </div>
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  queryAllUser,
  queryUserNameList,
  logout,
  tryToProjectSystem,
  tryToIncomeStreamSystem,
  tryToOutlayStreamSystem,
  tryToAdminSystem
} from "@/api/userApi";
import store from "@/store";
import { constObjs } from "@/const/const";
// 导入ElMessageBox，单独引用
import { ElMessage, ElMessageBox } from "element-plus";
import {
  incomeStreamRules,
  outlayStreamRules,
  projectRules,
  userPermissionRules
} from "@/const/rules";
import { queryAllProject } from "@/api/projectApi";
import { queryAllIncomeStream } from "@/api/incomestreamApi";
import { queryAllOutlayStream } from "@/api/outlaystreamApi";

export default defineComponent({
  name: "home",
  setup() {
    // get data base on the route
    const route = useRoute();
    const router = useRouter();
    const nowAsideNavIndex = ref<number>(0);
    // ------------------------aside------------------
    const toProjectSystem = async () => {
      // 查询项目
      // try to goto projectsystem
      if (!store.state.nowUserPermissionList.includes("projectSystem")) {
        return;
      }
      await tryToProjectSystem().then(async () => {
        nowAsideNavIndex.value = 0;
        // get data from db firstly because the tablepattern maybe changed in this function
        await queryAllProject();

        // change store(to subsystem.vue)
        store.state.formPattern = JSON.parse(
          JSON.stringify(constObjs.projectFormPattern)
        );
        // FORM RULES
        store.state.formRules = projectRules;
        store.state.nowSystem = "project";
        // queryAllProject是异步方法，为了保证先运行完异步再赋值tablepattern所以延迟0.5s再赋值tablepattern
        store.state.tablePattern = JSON.parse(
          JSON.stringify(constObjs.projectsTablePattern)
        );
        // UserNameList will be used when choosing projectManager
        await queryUserNameList();

        router.push({
          name: "projectsystem"
        });
      });
    };
    const toIncomeStreamSystem = async () => {
      // the stream data will show after a project is selected
      // try to goto incomestreamsystem
      if (
        store.state.projectList == undefined ||
        store.state.projectList.length <= 0
      ) {
        ElMessage.error("请先查询培训项目以后再查询收入|支出流水");
        return;
      }
      await tryToIncomeStreamSystem().then(async () => {
        nowAsideNavIndex.value = 1;
        // should queryAllIncomeStream firstly, because the tablepattern of incomestream maybe changed after queryed
        await queryAllIncomeStream().then(() => {
          // change store(to subsystem.vue)
          store.state.formPattern = JSON.parse(
            JSON.stringify(constObjs.incomeStreamFormPattern)
          );
          // FORM RULES
          store.state.formRules = incomeStreamRules;
          store.state.nowSystem = "incomestream";
          // 同理，延时0.5s赋值tablepattern
          store.state.tablePattern = JSON.parse(
            JSON.stringify(constObjs.incomeStreamTablePattern)
          );
        });
        router.push({
          name: "incomestreamsystem"
        });
      });
    };
    const toOutlayStreamSystem = async () => {
      // the stream data will show after a project is selected
      // try to goto outlaystreamsysrem
      if (
        store.state.projectList == undefined ||
        store.state.projectList.length <= 0
      ) {
        ElMessage.error("请先查询培训项目以后再查询收入|支出流水");
        return;
      }
      await tryToOutlayStreamSystem().then(async () => {
        nowAsideNavIndex.value = 2;
        await queryAllOutlayStream().then(() => {
          store.state.formPattern = JSON.parse(
            JSON.stringify(constObjs.outlayStreamFormPattern)
          );
          // FORM RULES
          store.state.formRules = outlayStreamRules;
          store.state.tablePattern = JSON.parse(
            JSON.stringify(constObjs.outlayStreamTablePattern)
          );
          store.state.nowSystem = "outlaystream";
          router.push({
            name: "outlaystreamsystem"
          });
        });
      });
    };
    // admin
    const toAdminSystem = async () => {
      // await querySystemSetting("123");
      await tryToAdminSystem().then(async () => {
        nowAsideNavIndex.value = 3;
        store.state.formPattern = JSON.parse(
          JSON.stringify(constObjs.userPermissionFormPattern)
        );
        store.state.formRules = JSON.parse(JSON.stringify(userPermissionRules));
        store.state.tablePattern = JSON.parse(
          JSON.stringify(constObjs.userPermissionTablePattern)
        );
        store.state.formRules = JSON.parse(JSON.stringify(userPermissionRules));
        // DATA WILL BE LOADED AFTER GOTO THE PROJECTSYSTEM
        await queryAllUser();
        router.push({
          name: "adminsystem"
        });
      });
    };

    if (
      localStorage.getItem("store") &&
      localStorage.getItem("historyRouteName") == JSON.stringify(route.name)
    ) {
      store.replaceState(
        Object.assign({}, JSON.parse(localStorage.getItem("store") as string))
      );
    }
    // reset store when F5
    window.addEventListener("beforeunload", () => {
      localStorage.setItem("store", JSON.stringify(store.state));
      localStorage.setItem("historyRouteName", JSON.stringify(route.name));
    });
    // 给内容不足以撑满浏览器可视高度的页面添加以下设置，通过动态（监测浏览器窗口变化）设置页面容器最低高度，也就是footer组件正常加载，只是footer的兄弟容器的高度变化了，自身的位置也会变化。
    // footer + head = 170px
    const minHeight = ref<number>(document.documentElement.clientHeight - 160);

    const isShowUserMessage = ref<boolean>(false);

    // onMounted
    onMounted(() => {
      // 重新计算footer的兄弟main的minheight
      window.onresize = () => {
        minHeight.value = document.documentElement.clientHeight - 160;
      };
    });

    const showUserMessage = () => {
      // show usermessage dialog
      isShowUserMessage.value = true;
    };

    // logout before confirmed
    const clickLogoutButton = () => {
      ElMessageBox.confirm("您确定要退出登录吗？", "提示", {
        confirmButtonText: "退出登录",
        cancelButtonText: "不了不了",
        type: "info",
        center: true
      }).then(() => {
        // logout, and clean the data in the store.state
        logout();
        // show message
        ElMessageBox({
          type: "success",
          message: "已退出登录"
        });
      });
    };
    return {
      router,
      route,
      nowAsideNavIndex,
      isShowUserMessage,
      minHeight,
      nowUserName: computed(() => store.state.username),
      // judge if now is login page
      isLogin: computed(() => router.currentRoute.value.path === "/login"),
      showUserMessage,
      clickLogoutButton,
      toProjectSystem,
      toIncomeStreamSystem,
      toOutlayStreamSystem,
      toAdminSystem
    };
  }
});
</script>

<style>
.el-container .index-el-header {
  height: 60px;
}
/* ------------------index header----------------------- */
.div-index-header {
  display: flex;
  background-color: rgb(56, 61, 65);
  height: 100%;
}
.div-index-header-logo {
  max-height: 60px;
  max-width: 871px;
}
.el-container h1 {
  margin: 0;
  padding: 0;
}
.div-index-header-nav {
  display: flex;
  align-items: center;
  margin: 0 2px 0 auto;
}
.div-index-header-nav-item {
  display: flex;
  align-items: center;
  height: 100%;
  border-right: 1px solid black;
}
.div-index-header-nav .el-input {
  margin-right: 15px;
}
.div-index-header-nav .el-input__inner {
  background-color: rgb(79, 84, 87);
  border: none;
  border-radius: 0;
  width: 250px;
}
.div-index-header-nav-item > .el-button {
  padding: 0 15px;
  color: #ffffff;
}
.div-index-header-nav-item .el-button {
  font-size: 15px;
  height: 100%;
  width: 100%;
}
.div-index-header-nav-item > .el-button:hover {
  border-bottom: 4px solid #ffffff;
  color: #ffffff;
}
.div-index-header-nav-item > .el-button:focus {
  /* border-bottom: 2px solid #ffffff; */
  color: #ffffff;
}
.div-index-header-nav .el-button-search {
  border-left: 1px solid rgb(102, 107, 110);
  padding: 0 15px;
  color: #ffffff;
}

/* ------------------index aside----------------------- */
/* ------------------index aside----------------------- */
.el-container #el-aside-nav {
  /* 宽度在el-aside width中设置 */
  background-color: rgb(62, 65, 81);
  overflow-y: hidden;
}
.div-index-aside-nav {
  display: flex;
  flex-direction: column;
  /* 继承父盒子的宽度 */
  width: 100%;
  max-height: 600px;
}
/* .div-index-aside-nav :last-child {
  border: none;
} */
.div-index-aside-nav-item {
  display: flex;
  align-content: center;
  flex-direction: column;
  border-bottom: 1px solid #616574;
}
.div-index-aside-nav-item .el-button {
  color: rgb(62, 65, 81);
  border: none;
  border-radius: 0px;
  margin: 0;
  padding: 0;
  height: 150px;
}
.div-index-aside-nav-item .el-button:hover {
  color: rgb(47, 50, 61);
}
.div-index-aside-nav-item .el-button-hide-aside {
  height: 12px;
  padding: 0;
  /* background: rgb(74, 80, 100); */
  background: #42485b;
  color: #ffffff;
  width: 100%;
}

/* -----------------------------icon------------------------- */
.el-icon-projectsystem::before,
.el-icon-projectsystem-focus::before {
  /* 占位符 */
  content: "\66ff";
  font-size: 120px;
  visibility: hidden;
}
.el-icon-adminsystem::before,
.el-icon-adminsystem-focus::before,
.el-icon-incomestreamsystem::before,
.el-icon-incomestreamsystem-focus::before,
.el-icon-outlaystreamsystem::before,
.el-icon-outlaystreamsystem-focus::before {
  /* 占位符 */
  content: "\66ff";
  font-size: 120px;
  visibility: hidden;
}
.el-icon-projectsystem {
  background: url("../../public/icon-projectsystem.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
}
.el-icon-incomestreamsystem {
  background: url("../../public/icon-incomestreamsystem.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
}
.el-icon-outlaystreamsystem {
  background: url("../../public/icon-outlaystreamsystem.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
}
.el-icon-adminsystem {
  background: url("../../public/icon-adminsystem.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
}
/* ---------------------hover, visited------------------------ */
.el-icon-projectsystem-focus,
.el-icon-projectsystem:hover {
  background: url("../../public/icon-projectsystem-hover.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  box-shadow: -1px 1px 2px 0px #ccc, 1px -1px 2px 0px #ccc,
    -1px -1px 2px 0px #ccc, 1px 1px 2px 0px #ccc;
}
.el-icon-incomestreamsystem-focus,
.el-icon-incomestreamsystem:hover {
  background: url("../../public/icon-incomestreamsystem-hover.png") center
    no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  box-shadow: -1px 1px 2px 0px #ccc, 1px -1px 2px 0px #ccc,
    -1px -1px 2px 0px #ccc, 1px 1px 2px 0px #ccc;
}
.el-icon-outlaystreamsystem:hover,
.el-icon-outlaystreamsystem-focus {
  background: url("../../public/icon-outlaystreamsystem-hover.png") center
    no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  box-shadow: -1px 1px 2px 0px #ccc, 1px -1px 2px 0px #ccc,
    -1px -1px 2px 0px #ccc, 1px 1px 2px 0px #ccc;
}
.el-icon-adminsystem:hover,
.el-icon-adminsystem-focus {
  background: url("../../public/icon-adminsystem-hover.png") center no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  box-shadow: -1px 1px 2px 0px #ccc, 1px -1px 2px 0px #ccc,
    -1px -1px 2px 0px #ccc, 1px 1px 2px 0px #ccc;
}
/* ------------------index aside----------------------- */

/* --------------------footer-------------------------- */
/* --------------------footer-------------------------- */
.div-footer {
  display: flex;
  flex-direction: column;
}
.div-footer .el-button {
  font-size: 13px;
  color: rgb(0, 0, 0);
}
.div-footer .el-button:hover {
  border-bottom: 1px solid black;
}
.div-footer-line1,
.div-footer-line2 {
  display: flex;
  justify-content: center;
  font-size: 13px;
  color: rgb(0, 0, 0);
}

/* ------------------自定义element-plus样式------------------ */
/* 固定头部和侧边栏 */
.el-button,
.el-button:hover {
  border-radius: 0;
}
.el-container {
  background: rgb(234, 237, 241);
}

.el-header {
  margin: 0;
  padding: 0;
}
/* main内容可滚动 */
.el-main {
  background: rgb(234, 237, 241);
}
/* 选择器在一行显示 */
.el-select-dropdown__item {
  display: block;
}
.el-breadcrumb__inner is-link {
  padding-top: 2px;
}
.el-button {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
.el-input-number .el-input .el-input__inner {
  text-align: left;
}
.el-message-box__btns .el-button {
  font-size: 12px;
  border: 1px solid #0d92d7;
  background-color: #ffffff;
  font-family: "Microsoft YaHei";
  color: #0d92d7;
}
.el-message-box__btns .el-button:hover {
  background-color: rgb(243, 248, 255);
}
.el-message-box__message p {
  color: #000000;
}
</style>
